package com.zbcz.crm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.Customer
import com.zbcz.crm.bean.BaseBean
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import com.zbcz.crm.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class UserAddViewModel : ViewModel() {


    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)

    val mResponse = MutableLiveData<Boolean>()


    fun addCustomer(data: Customer) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = addCustomerSuspend(data)
                withContext(Dispatchers.Main) {
                    if (result?.success == true) {
                        mResponse.postValue(true)
                        ToastUtils.show("添加成功")
                    } else {
                        result?.message?.let { ToastUtils.show(it) }
                        mResponse.postValue(false)
                    }
                }
            }
        }
    }


    private suspend fun addCustomerSuspend(data: Customer): BaseBean<Object>? {
        try {
            return mApi.addCustomer(
                data, token = SharedPreferencesManager.getToken(
                    CrmApplication.mApplication
                )
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

}